//
//  WJComposeTextView.swift
//  WJWeiBo
//
//  Created by wangjun on 16/7/28.
//  Copyright © 2016年 wangjun. All rights reserved.
//

import UIKit

class WJComposeTextView: UITextView {
    // 重写父类已有属性 监听变化
    override var font: UIFont?{
        didSet{
            placeholderLabel.font = font
        }
    }
    // 设置占位文字
    var placeholder: String?{
        didSet{
            placeholderLabel.text = placeholder
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        self.textContainer.maximumNumberOfLines = 1
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        // 添加控件
        addSubview(placeholderLabel)
        // 添加约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -10))
        // 通过监听系统通知来得到当前textView 的文字改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "valueChange", name: UITextViewTextDidChangeNotification, object: nil)
        
    }
    // 通知方法
    func valueChange(){
        placeholderLabel.hidden = self.hasText()
    }
    
    // 占位文字
    private lazy var placeholderLabel: UILabel = {
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.textColor = UIColor.grayColor()
        return lab
    }()
}
